﻿@using BlazorMonaco.Editor
@using FormBuilder.Components
@using FormBuilder.Components.Form
@using FormBuilder.Factories
@using FormBuilder.Models
@using FormBuilder.Models.Layout
@using Radzen
@using Radzen.Blazor
@using System.Text.Json.Nodes
@using System.Text.Json
@inject DialogService dialogService
@inject IFakerDataServiceFactory fakerDataServiceFactory

<RadzenSteps>
    <Steps>
        <RadzenStepsItem Text="Input data (JSON)">
            <StandaloneCodeEditor @ref=editor OnDidInit="HandleOnDidInit" OnDidChangeModelContent="HandleOnEditorContentChanged" ConstructionOptions="EditorConstructionOptions" CssClass="jsonEditor" />
        </RadzenStepsItem>
        <RadzenStepsItem Text="Viewer" Disabled="@(input == null)">
            <FormViewer Context="@context" IsEditModeEnabled="false"></FormViewer>
        </RadzenStepsItem>
    </Steps>
</RadzenSteps>

@code {
    private StandaloneCodeEditor editor;
    [Parameter] public FormRecord Form { get; set; }
    [Parameter] public Template Template { get; set; }
    [Parameter] public List<string> SupportedLanguages { get; set; }
    FormRecord copyRecord { get; set; }
    WorkflowContext context { get; set; }
    JsonObject input { get; set; }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (copyRecord == null && Form != null)
        {
            copyRecord = JsonSerializer.Deserialize<FormRecord>(JsonSerializer.Serialize(Form));
        }
    }

    private async Task HandleOnDidInit()
    {
        await GenerateFakeData();
    }

    private async Task HandleOnEditorContentChanged()
    {
        var value = await editor.GetValue();
        try
        {
            input = JsonObject.Parse(value).AsObject();
            context = WorkflowContext.CreateOneStepWorkflow(copyRecord, input, Template, SupportedLanguages);
        }
        catch
        {
            input = null;    
        }
    }

    private async Task GenerateFakeData()
    {
        var serialized = await fakerDataServiceFactory.Generate(Form.CorrelationId);
        var json = JsonSerializer.Serialize(JsonObject.Parse(serialized), new JsonSerializerOptions { WriteIndented = true });
        await editor.SetValue(json);
    }

    private StandaloneEditorConstructionOptions EditorConstructionOptions(StandaloneCodeEditor editor)
    {
        return new StandaloneEditorConstructionOptions
        {
            AutomaticLayout = true,
            Language = "json",
            Value = "{}"
        };
    }
}